<template>
  <div class="shopping-cart">
    <!-- ...其他代码... -->
    <table v-if="cartItems.length > 0" class="cart-table">
      <thead>
        <tr>
          <th>订单详情</th>
          <th>图片</th>
          <th>单价</th>
          <th>数量</th>
          <th>总价</th>
          <th>烹饪方式</th>
          <th>配料</th>
          <th>--</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in cartItems" :key="item.id">
          <td>{{ item.name }}</td>
          <td><img :src="item.src" alt="商品图片" class="item-image" /></td>
          <td>{{ item.price }}元</td>
          <td>{{ item.quantity }}</td>
          <td>{{ item.price * item.quantity }}元</td>
          <!-- 用户选择的配料 -->
          <!-- <td>{{ item.selectedOptions | optionsFilter }}</td> -->
          <!-- 烹饪方式 -->
          <!-- <td>{{ item.cookingMethod }}</td> -->
          <td>{{ item.selectedCookingMethod }}</td>
          <!-- 渲染烹饪方式 -->
          <td>
            <span v-for="(option, index) in item.selectedOptions" :key="index">
              {{ option }},
            </span>
          </td>
          <td>
            <el-button @click="delcart(item.id)">删除信息</el-button>
          </td>
        </tr>
        <!-- 底部行显示总价格 -->
        <tr>
          <td colspan="6">总计：</td>
          <td>{{ totalAmount }}元</td>
        </tr>
      </tbody>
    </table>
    <!-- ...其他代码... -->
    <p v-else>购物车是空的。</p>
    <!-- 结算按钮 -->
    <el-button v-if="cartItems.length > 0" type="primary" @click="checkout">结算</el-button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "ShoppingCart",

  computed: {
    cartItems() {
      return this.$store.state.cart; // 从Vuex store获取购物车数据
    },
    totalAmount() {
      // 计算总价格
      return this.cartItems.reduce((total, item) => {
        return total + item.price * item.quantity;
      }, 0);
    },
    returnRecordMsg() {
      return this.cartItems.map(item => item.name).join('+');
    },
    returnPriceMsg() {
      return this.totalAmount;
    }
  },
  methods: {
    checkout() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
      const day = currentDate.getDate().toString().padStart(2, '0');
      const hour = currentDate.getHours().toString().padStart(2, '0');
      const minute = currentDate.getMinutes().toString().padStart(2, '0');
      const second = currentDate.getSeconds().toString().padStart(2, '0');
      const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      let record = {
        userId: this.$route.query.loginUserId,
        names: this.returnRecordMsg,
        prices: this.returnPriceMsg,
        date: formattedDate
      };
      // 结算逻辑
      console.log("结算按钮被点击，总价格为:", record);
      axios.post("http://localhost:8080/checkOut", record).then((result) => {
        console.log(result.data.data);
      }).catch((error) => {
        console.error("请求失败:", error);
      });
      // 可以在这里添加跳转到结算页面的逻辑或调用后端API
      this.$store.dispatch('clearCart').then(() => {
          // 商品删除成功后的操作，例如提示用户
          this.$message.success('购物车已经清空！');
        })
      
    },
    delcart(itemId) {
      this.$store.dispatch('removeFromCart', itemId)
        .then(() => {
          // 商品删除成功后的操作，例如提示用户
          this.$message.success('商品已从购物车删除！');
        })
        .catch((error) => {
          // 处理错误情况
          this.$message.error('商品删除失败。');
          console.error("Error removing item from cart: ", error);
        });
    }
  },
};
</script>


<style scoped>
.cart-table {
  width: 100%;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.cart-table th,
.cart-table td {
  border: none;
  padding: 8px;
  text-align: left;
}

.cart-table th {
  background-color: #f2f2f2;
}

.item-image {
  width: 50px;
  /* 根据需要调整图片大小 */
  height: auto;
}
</style>